package com.tencent.examples.blueking.mysql.service;

import com.tencent.examples.blueking.mongo.extend.biz.CrudBiz;
import com.tencent.examples.blueking.mysql.model.BkMessage;
import com.tencent.examples.blueking.mysql.repository.MessageRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class MessageService extends CrudBiz<MessageRepository> {

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * 查询
     */
    public BkMessage findByMx() {
        return dao.findByMx("111");
    }

    /**
     * 新增
     */
    public void messageSave(BkMessage message) {
        dao.save(message);
    }

    /**
     * 新增
     */
    public void save(BkMessage message) {
        entityManager.persist(message);
    }

    /**
     * 更新
     */
    public void update(BkMessage message) {
        entityManager.merge(message);
    }

    public Page<BkMessage> getMessageList(Pageable pageable, BkMessage message) {
        //规格定义
        Specification<BkMessage> specification = new Specification<BkMessage>() {

            /**
             * 构造断言
             * @param root 实体对象引用
             * @param criteriaQuery 规则查询对象
             * @param criteriaBuilder 规则构建对象
             * @return 断言
             */
            @Override
            public Predicate toPredicate(Root<BkMessage> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>(); //所有的断言
                if (StringUtils.isNotBlank(message.getMx())) {
                    predicates.add(criteriaBuilder.equal(root.get("mx").as(String.class), message.getMx()));
                }
                if (message.getSync() != null) {
                    predicates.add(criteriaBuilder.equal(root.get("sync").as(Integer.class), message.getSync()));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
            }
        };
        //查询
        return dao.findAll(specification, pageable);
    }
}
